﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using tenpay;

namespace OnlinePayment
{
    /// <summary>
    /// 创建支付参数
    /// </summary>
    public class PayParam
    {
        #region 获取当前ip
        public static string GetRealIp()
        {
            string UserIP;
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return UserIP;
        }
        #endregion

        #region 第三方支付参数
　
        #region 支付宝参数
        public string AlipayParam(int rp, string body, decimal vMoney, string userID, ref string exchangeID, string returnUrl, string notifyUrl)
        {
            Random random = new Random(System.Environment.TickCount);
            string out_trade_no = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + random.Next(10000, 99999);
            exchangeID = out_trade_no;

            //业务参数赋值；
            string gateway = ConfigurationManager.AppSettings["AlipayGateway"].ToString();
            string service = ConfigurationManager.AppSettings["AlipayService"].ToString();//服务标识
            string partner = ConfigurationManager.AppSettings["AlipayPartner"].ToString();//合作伙伴ID
            string sign_type = ConfigurationManager.AppSettings["AlipaySignType"].ToString();//加密方式

            string subject = "";
            if (rp == 1)
                subject = ConfigurationManager.AppSettings["AlipaySubject"].ToString();//商品名称 充值
            else if (rp == 2)
                subject = ConfigurationManager.AppSettings["AlipaySubjectPay"].ToString();//商品名称 付款
            else
                subject = "";

            string input_charset = ConfigurationManager.AppSettings["AlipayInputCharSet"].ToString();//编码类型
            string payment_type = ConfigurationManager.AppSettings["AlipayPaymentType"].ToString();//支付类型	
            string total_fee = Math.Round(vMoney, 2).ToString();//金额 0.01～50000.00
            string show_url = ConfigurationManager.AppSettings["AlipayShowUrl"].ToString();
            string seller_email = ConfigurationManager.AppSettings["AlipaySellerEmail"].ToString();//卖家账号
            string key = ConfigurationManager.AppSettings["AlipayKey"].ToString();//安全校验码
            string return_url = returnUrl; //返回页地址
            string notify_url = notifyUrl; //通知页地址
            string paymethod = ConfigurationManager.AppSettings["AlipayPayMethod"].ToString();//bankPay cartoon directPay

            string[] para ={
            "service="+service,
            "partner=" + partner,
            "seller_email=" + seller_email,
            "out_trade_no=" + out_trade_no,
            "subject=" + subject,
            "body=" + body,
            "total_fee=" + total_fee, 
            "show_url=" + show_url,
            "payment_type=" + payment_type,
            "paymethod=" + paymethod,
            "notify_url=" + notify_url,
            "return_url=" + return_url,
            "_input_charset=" + input_charset,
            "defaultbank=ICBC"
            };

            string aliay_url = AliPay.CreatUrl(
                para,
                input_charset,
                sign_type,
                key
                );

            string alipayStr = "";
            for (int i = 0; i < para.Length; i++)
                alipayStr += para[i] + "&";
            alipayStr += "sign=" + aliay_url;

            return gateway + alipayStr;
        }
        #endregion

        #region 财付通参数
        public string TenpayParam(int rp, string body, decimal vMoney, string  userID, ref string exchangeID, string returnUrl, string notifyUrl)
        {
            //设置支付参数
            string bargainor_id = ConfigurationManager.AppSettings["TenpayBargainorId"].ToString();//商户号
            string key = ConfigurationManager.AppSettings["TenpayKey"].ToString();//密钥
            string sp_billno = DateTime.Now.ToString("HHmmss") + TenpayUtil.BuildRandomStr(4);//商户订单号，不超过32位，财付通只做记录，不保证唯一性
            string transaction_id = bargainor_id + DateTime.Now.ToString("yyyyMMdd") + sp_billno;//财付通订单号，10位商户号+8位日期+10位序列号，需保证全局唯一
            string return_url = returnUrl;

            exchangeID = transaction_id;

            PayRequestHandler reqHandler = new PayRequestHandler(System.Web.HttpContext.Current);//创建PayRequestHandler实例
            reqHandler.setKey(key);//设置密钥 
            reqHandler.init();//初始化
            reqHandler.setParameter("bargainor_id", bargainor_id);			//商户号
            reqHandler.setParameter("sp_billno", sp_billno);				//商家订单号
            reqHandler.setParameter("transaction_id", transaction_id);		//财付通交易单号
            reqHandler.setParameter("return_url", return_url);				//支付通知url

            if (rp == 1)
                reqHandler.setParameter("desc", ConfigurationManager.AppSettings["TenpayDesc"].ToString());	//商品名称 充值
            else if (rp == 2)
                reqHandler.setParameter("desc", ConfigurationManager.AppSettings["TenpayDescPay"].ToString());	//商品名称 付款
            else
                reqHandler.setParameter("desc", "");

            reqHandler.setParameter("total_fee", (Convert.ToInt32(Convert.ToDecimal(vMoney) * 100)).ToString());    //商品金额,以分为单位
            reqHandler.setParameter("bank_type", ConfigurationManager.AppSettings["TenpayBankType"].ToString());	//财付通支付方式
            reqHandler.setParameter("cs", ConfigurationManager.AppSettings["TenpayCs"].ToString());	//编码格式
            reqHandler.setParameter("cmdno", ConfigurationManager.AppSettings["TenpayCmdno"].ToString());	//使用财付通支付标签
            reqHandler.setParameter("spbill_create_ip", GetRealIp());
            reqHandler.setParameter("attach", body);	 //商家自己的数据包

            string requestUrl = reqHandler.getRequestURL();//获取请求带参数的url

            return requestUrl;
        }
        #endregion

        #region 银联参数
        public string ChinaPayParam(int rp, string body, decimal vMoney, string  userID, ref string exchangeID, string returnUrl, string notifyUrl)
        {
            Random random = new Random(System.Environment.TickCount);
            string out_trade_no = DateTime.Now.ToString("yyyyMMddHHmmss") + random.Next(10, 99);

            exchangeID = out_trade_no;

            string Action = ConfigurationManager.AppSettings["ChinaPayAction"].ToString();//支付接入地址
            string MerId = ConfigurationManager.AppSettings["ChinaPayMerId"].ToString();//商户号，必填
            string BusiId = ConfigurationManager.AppSettings["ChinaPayBusiId"].ToString();//业务编号，选填
            string OrdId = out_trade_no;
            string OrdAmt = (Convert.ToInt32(Convert.ToDecimal(vMoney) * 100)).ToString();//订单金额，单位：分，必填
            string CuryId = ConfigurationManager.AppSettings["ChinaPayCuryId"].ToString();//订单币种，必填
            string Version = ConfigurationManager.AppSettings["ChinaPayVersion"].ToString();//支付接入版本号，必填
            string BgRetUrl = returnUrl;//后台交易接收URL，必填
            string PageRetUrl = notifyUrl;//页面交易接收URL，必填
            string GateId = ConfigurationManager.AppSettings["ChinaPayGateId"].ToString();//支付网关号，选填

            string OrdDesc = "";
            if (rp == 1)
                OrdDesc = ConfigurationManager.AppSettings["ChinaPayOrdDesc"].ToString();//订单描述，选填 充值
            else if (rp == 2)
                OrdDesc = ConfigurationManager.AppSettings["ChinaPayOrdDescPay"].ToString();//订单描述，选填 付款
            else
                OrdDesc = "";

            string ShareType = ConfigurationManager.AppSettings["ChinaPayShareType"].ToString();//分账类型，必填
            string ShareData = ConfigurationManager.AppSettings["ChinaPayShareData"].ToString() + OrdAmt;//商户分账数据，必填
            string Priv1 = body;//商户自填信息
            string CustomIp = GetRealIp();//用户提交订单的IP地址，选填
            string ChkValue = "";//签名数据，必填

            ChinaPayUtils.priKeyPath = ConfigurationManager.AppSettings["ChinaPayPriKeyPath"].ToString();
            string plainData = MerId + BusiId + OrdId + OrdAmt + CuryId + Version + BgRetUrl + PageRetUrl + GateId + ShareType + ShareData + Priv1 + CustomIp;
            ChkValue = ChinaPayUtils.signData(MerId, plainData);

            return Action + "?" + "MerId=" + MerId + "&BusiId=" + BusiId + "&OrdId=" + OrdId + "&OrdAmt=" + OrdAmt + "&CuryId=" + CuryId + "&Version=" + Version + "&BgRetUrl=" + BgRetUrl + "&PageRetUrl=" + PageRetUrl + "&GateId=" + GateId + "&OrdDesc=" + OrdDesc + "&ShareType=" + ShareType + "&ShareData=" + ShareData + "&Priv1=" + Priv1 + "&CustomIp=" + CustomIp + "&ChkValue=" + ChkValue;
        }
        #endregion

        #region 获取支付参数
        public string GetPayParam(int flag, int rp, string body, decimal vMoney, string  userID, ref string exchangeID, string returnUrl, string notifyUrl)
        {
            if (flag == 1)
                return AlipayParam(rp, body, vMoney, userID, ref exchangeID, returnUrl, notifyUrl);
            else if (flag == 2)
                return TenpayParam(rp, body, vMoney, userID, ref exchangeID, returnUrl, notifyUrl);
            else if (flag == 3)
                return ChinaPayParam(rp, body, vMoney, userID, ref exchangeID, returnUrl, notifyUrl);
            else
                return "";
        }
        #endregion

        #endregion
    }
}
